import { create } from "zustand";

type AppStore = {
  userInfo: any;
  clearUserInfo: () => void;
  updateUserInfo: (info: any) => void;

  // 职位列表
  postList: any[] | undefined;
  updatePostList: (list: any[]) => void;

  // 全局的，是否在登录状态
  appLoggingIn: boolean;
  setAppLoggingIn: (flag?: boolean) => void;

  authRoles: undefined | Map<string, { prCode: string; caption: string }>;
  setAuthRoles: (payload: any) => void;

  // 退出登录（清除一些状态）
  logout: () => void;
};

const useAppStore = create<AppStore>((set, get) => ({
  userInfo: undefined,
  clearUserInfo: () => set({ userInfo: undefined }),
  updateUserInfo: (userInfo) => set({ userInfo }),

  postList: undefined,
  updatePostList: (postList) => set({ postList }),

  appLoggingIn: false,
  setAppLoggingIn: (flag = false) => set({ appLoggingIn: flag }),

  authRoles: undefined,
  setAuthRoles: (payload: any) => {
    if (payload) {
      const map = new Map();
      payload.forEach((item) => {
        map.set(item.prCode, item);
      });

      set({ authRoles: map });
    } else {
      set({ authRoles: undefined });
    }
  },

  logout() {
    const self = get();
    self.clearUserInfo();
    self.setAuthRoles(undefined);
  },
}));

export default useAppStore;
